<template>
  <!-- 聊天对话 -->
  <div
    class="Dialogue"
    v-if="isLogin"
  >
    <div class="tab">
      <div
        :class="['item', 'flexcc-col', { active: activeTab === index }]"
        v-for="(item, index) in tab"
        :key="index"
        @click="setTab(index)"
      >
        <component
          :is="item.icon"
          style="height: 20px"
        ></component>
        <div class="text">{{ t(item.name) }}</div>
      </div>
    </div>

    <div
      class="list"
      v-if="activeTab === 0"
    >
      <div
        class="item"
        v-for="(item, index) in listData"
        :key="item.id"
        @click="openDialog(item)"
      >
        <div class="avatar">
          <img
            :src="item.customerAvatar || defaultAvatar"
            alt=""
          />
          <div
            class="num flexcc"
            v-if="item.unreadNum > 0"
          >
            {{ item.unreadNum }}
          </div>
        </div>
        <div class="flexsc">
          {{ item.customerName }}
        </div>
      </div>
    </div>

    <div
      v-if="activeTab === 1"
      class="history"
    >
      <div
        class="main"
        ref="mainEl"
      >
        <div
          v-if="isLoadmore"
          class="flexcc mb-2 mt-1"
          @click="loadmore"
        >
          {{ t('dialogue.viewHistory') }}
        </div>

        <div
          :class="['item', 'mb-2', { self: isSelf(sendingCustomerId) }]"
          v-for="{ id, customerAvatar, customerName, createTime, showTime, content, sendingCustomerId, state } in infoList"
          :key="id"
        >
          <div
            v-if="showTime"
            class="time flexcc"
          >
            {{ dateFilter(createTime) }}
          </div>
          <div class="user flexss">
            <img
              :src="customerAvatar || defaultAvatar"
              class="avatar mr-1"
            />
            <div>
              <div class="n">
                <div class="name">{{ customerName }}</div>
              </div>
              <div :class="['content', `state-${state}`]">{{ content }}</div>
            </div>
          </div>
        </div>

        <!-- <div class="flexcc">No more at the moment...</div> -->
      </div>
      <div class="myfooter mt-2">
        <div class="grid">
          <div class="flexsc">
            <el-input
              v-model.trim="content"
              :placeholder="t('dialogue.pleaseInput')"
              :autosize="{ minRows: 4, maxRows: 4 }"
              @keydown.enter="handleSend"
            />
          </div>
          <el-button
            type="primary"
            @click="handleSend"
          >
            {{ t('dialogue.send') }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onBeforeMount, onUnmounted, nextTick, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useDialogue from '@/stores/dialogue'
import useLogin from '@/stores/login'
import { sessionApi, getInfoListApi, getUnreadInfoListApi, getSendingUnreadInfoListApi, getListApi, deletePersonApi, blackPersonApi } from '@/service/common'
import { dateFormat } from '@/utils'
import { useI18n } from 'vue-i18n'
import moment from 'moment'

import { Menu, ChatLineSquare } from '@element-plus/icons-vue'

const storeLogin = useLogin()

const { t, locale } = useI18n()
watch(locale, (n) => {
  init()
})

onBeforeMount(() => {
  init()
})

onUnmounted(() => {
  clearInterval(timerInfo.value)
  clearInterval(timerList.value)
})

const router = useRouter()
const route = useRoute()

const store = useDialogue()
const { setDialogVisible, setActivePerson, reset } = store

const tab = markRaw([
  {
    icon: Menu,
    name: 'dialogue.DialogueList'
  },
  {
    icon: ChatLineSquare,
    name: 'dialogue.Dialogue'
  }
])
const activeTab = ref(0)
const setTab = (index) => {
  if (index === 1 && !store.activePerson.customerId) {
    return
  }
  activeTab.value = index
}

watch([activeTab, () => store.activePerson.customerId], (n) => {
  resetData()

  if (n[0] === 1) {
    if (n[1]) {
      getInfoList()

      if (!timerInfo.value) {
        // 定时拉取未读
        timerInfo.value = setInterval(() => {
          getUnreadInfoList()
          getSendingUnreadInfoList()
        }, 1000 * 10)
      }
    } else {
      activeTab.value = 0
    }

    clearInterval(timerList.value)
    timerList.value = null
  }

  if (n[0] === 0) {
    const fn = () => {
      getList()
      return fn
    }
    if (!timerList.value) {
      timerList.value = setInterval(fn(), 1000 * 10)
    }

    clearInterval(timerInfo.value)
    timerInfo.value = null
    reset()
  }
})
if (route.query.a === '1') {
  activeTab.value = 1
}

// 联系人列表
const listData = ref([])

// 默认头像
const defaultAvatar = new URL('@/assets/img/icon_touxiang_01.png', import.meta.url)

// 获取列表
const timerList = ref(null)
const getList = () => {
  getListApi().then(({ data }) => {
    const kf = data.find((item) => item.customerId === '0')

    if (kf) {
      data = data.filter((item) => item.customerId !== '0')
    }

    // 系统客服
    data.unshift({
      customerId: '0',
      customerName: t('dialogue.system'),
      customerAvatar: new URL('@/assets/img/kf.png', import.meta.url),
      unreadNum: kf ? kf.unreadNum : 0
    })

    listData.value = data
  })
}

// 获取会话数据
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 10 // 每页条数
})
const total = ref(0) // 总数
const infoList = ref([])
const getInfoList = (type = 'bottom') => {
  getInfoListApi(page.value, {
    receivedCustomerId: storeLogin.userInfo.id,
    sendingCustomerId: store.activePerson.customerId
  }).then(({ rows, total: tot }) => {
    rows.forEach((item) => {
      if (item.sendingCustomerId === 0) {
        item.customerName = t('dialogue.system')
        item.customerAvatar = new URL('@/assets/img/kf.png', import.meta.url)
      }
    })

    infoList.value = [...rows.reverse(), ...infoList.value]
    total.value = tot
    scrollTo(type)

    if (infoList.value.length >= total.value) {
      isLoadmore.value = false
    }
  })
}
// 加载更多
const isLoadmore = ref(true)
const loadmore = () => {
  page.value.pageNum++
  getInfoList('top')
}
// 重置
const resetData = () => {
  isLoadmore.value = true
  page.value.pageNum = 1
  infoList.value = []
  content.value = ''
}

// 每隔10分钟 显示时间
watch(
  infoList,
  (n) => {
    let t = null
    n.forEach((item, index) => {
      if (index === 0) {
        t = item.createTime
        item.showTime = true
      } else {
        if (item.createTime - t > 60 * 10) {
          t = item.createTime
          item.showTime = true
        }
      }
    })
  },
  { deep: true }
)

// 今年的不显示年 今天的只显示 时分
const dateFilter = (createTime) => {
  const isToday = moment.unix(parseInt(createTime)).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')
  const isThisYear = moment.unix(parseInt(createTime)).format('YYYY') === moment().format('YYYY')
  let str = ''
  if (isThisYear) {
    str = moment.unix(parseInt(createTime)).format(isToday ? 'HH:mm' : 'MM-DD HH:mm')
  } else {
    str = moment.unix(parseInt(createTime)).format('YYYY-MM-DD HH:mm')
  }
  return str
}

// 滚动到 顶部 底部
const mainEl = ref(null)
const scrollTo = (type) => {
  nextTick(() => {
    const obj = {
      top: 0,
      bottom: mainEl.value.scrollHeight
    }
    mainEl.value.scrollTo({ top: obj[type], behavior: 'smooth' })
  })
}

// 获取未读会话数据
const getUnreadInfoList = async () => {
  await getUnreadInfoListApi(null, {
    receivedCustomerId: storeLogin.userInfo.id,
    sendingCustomerId: store.activePerson.customerId
  }).then(({ data }) => {
    if (data.length) {
      infoList.value = [...infoList.value, ...data.reverse()]
      scrollTo('bottom')
    }
  })
}

// 查自己发的消息的已读状态
const getSendingUnreadInfoList = () => {
  getSendingUnreadInfoListApi(null, {
    receivedCustomerId: store.activePerson.customerId,
    sendingCustomerId: storeLogin.userInfo.id
  }).then(({ data }) => {
    if (data.length) {
      const ids = data.map((d) => d.id)
      infoList.value.forEach((item) => {
        item.state = ids.includes(item.id) ? '0' : '1'
      })
    } else {
      infoList.value.forEach((item) => {
        item.state = '1' // 状态(未读0 已读1)
      })
    }
  })
}

// 打开对话
const timerInfo = ref(null)
const openDialog = (item) => {
  if (store.activePerson.customerId === item.customerId) {
    return
  }
  activeTab.value = 1
  infoList.value = []
  isLoadmore.value = true
  page.value.pageNum = 1
  item.unreadNum = 0

  setActivePerson(item)
  // setDialogVisible(true)
}

const isSelf = (sendingCustomerId) => {
  return sendingCustomerId === storeLogin.userInfo.id
}

// 内容
const content = ref('')
const handleSend = () => {
  // console.log(store.activePerson.customerId)
  if (!content.value.trim()) return

  const params = {
    receivedCustomerId: store.activePerson.customerId,
    sendingCustomerId: storeLogin.userInfo.id,
    content: content.value
  }

  // console.log(params);
  sessionApi(params).then(async ({ data: { id, createTime, sendingCustomerId } }) => {
    await getUnreadInfoList()
    infoList.value.push({
      customerAvatar: storeLogin.userInfo.avatar,
      customerName: storeLogin.userInfo.userName,
      content: content.value,
      createTime,
      id,
      sendingCustomerId,
      state: '0'
    })
    content.value = ''
    scrollTo('bottom')
  })
}

// 删除
const handleDelete = () => {
  deletePersonApi(store.activePerson.customerId).then(({ msg }) => {
    ElMessage.success(msg)
    setDialogVisible(false)
    getList()
  })
}

// 拉黑
const handleBlack = () => {
  blackPersonApi(store.activePerson.customerId).then(({ msg }) => {
    ElMessage.success(msg)
    setDialogVisible(false)
    getList()
  })
}

const isLogin = computed(() => {
  return storeLogin.userInfo?.id
})

//
const init = () => {
  if (!isLogin.value) {
    return
  }
  getList()
}
</script>

<style scoped lang="scss">
.Dialogue {
  .tab {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    padding: 10px 0;
    box-shadow: 0px 4px 10px 0px rgba(171, 167, 195, 0.14);
    .item {
      color: #9d9fa5;
      &.active {
        color: #252628;
      }
      .text {
        margin-top: 5px;
      }
    }
  }

  .list {
    padding: 20px;
    height: calc(100vh - 110px);
    overflow: auto;
    .item {
      display: grid;
      grid-template-columns: 60px auto;
      gap: 10px;
      margin-bottom: 20px;
      height: 60px;
      .avatar {
        position: relative;
        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
        .num {
          position: absolute;
          top: 0;
          right: 0;
          background: var(--mainColor);
          padding: 0 5px;
          color: #fff;
          border-radius: 10px;
        }
      }
    }
  }

  .history {
    padding: 10px;
    .main {
      height: calc(100vh - 195px);
      overflow: auto;

      &::-webkit-scrollbar {
        width: 0px;
        height: 0px;
      }

      .item {
        .time {
          color: #ccc;
          font-size: 12px;
          margin-bottom: 10px;
        }
        .user {
          .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #fff;
          }
          .n {
            margin-bottom: 5px;
            .name {
              font-size: 12px;
            }
          }
        }
        .content {
          background: #f5f5f5;
          border-radius: 6px;
          padding: 10px;
          max-width: 70vw;
        }

        &.self {
          .user {
            flex-direction: row-reverse;
            .avatar {
              margin-right: 0;
              margin-left: 10px;
            }
            .n {
              text-align: right;
            }
          }

          .content {
            background: #10ecec;
            position: relative;

            &::after {
              content: '';
              display: block;
              position: absolute;
              left: -30px;
              top: 50%;
              width: 17px;
              height: 17px;
              transform: translateY(-50%);
            }
            &.state-0::after {
              background: url('@/assets/img/icon_weidu.png') no-repeat center / cover;
            }
            &.state-1::after {
              background: url('@/assets/img/icon_yidu.png') no-repeat center / cover;
            }
          }
        }
      }
    }
  }

  .myfooter {
    .grid {
      display: grid;
      grid-template-columns: auto 90px;
      gap: 10px;
      padding: 5px;
      background: #eaebec;
      border: 1px solid #eaebec;
      border-radius: 4px;
    }

    :deep(.el-input__wrapper) {
      background: none;
      border: 0;
      box-shadow: none;
    }

    .el-button {
      border-radius: 20px;
    }
  }
}
</style>
